package joomz;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import javax.script.Bindings;

/**
 * Local alias to "function" with configuration for script language.
 */
public class Event
    extends jbxml.Function
{
    public final static Reader SystemIn = new InputStreamReader(System.in);
    public final static Writer SystemOut = new OutputStreamWriter(System.out);
    public final static Writer SystemErr = new OutputStreamWriter(System.err);

    private final static java.util.List<String> JelaImports = new java.util.ArrayList<String>();
    private final static java.util.List<String> JelaDeclarations = new java.util.ArrayList<String>();
    static {

        JelaImports.add("import joomz.*;");

        JelaDeclarations.add("Game game = (Game)local.get(\"game\");");
        JelaDeclarations.add("Player player = game.getPlayer();");
        JelaDeclarations.add("Location location = player.getLocation();");
        JelaDeclarations.add("Action action = (Action)local.get(\"action\");");
        JelaDeclarations.add("{");
        JelaDeclarations.add("Action a2 = location.getActionFor(action);");
        JelaDeclarations.add("if (null != a2) action = a2;");
        JelaDeclarations.add("}");
        JelaDeclarations.add("Actor actor = action.getActor();");
        JelaDeclarations.add("Event event = actor.getEvent();");
    }

    public Event(){
        super();
        this.setLanguage("jela");
        this.setWriter(SystemOut);
        this.setErrorWriter(SystemErr);
        this.setReader(SystemIn);
        this.setImportStatements(JelaImports);
        this.setDeclarationStatements(JelaDeclarations);
    }
    

    public void init(Bindings local){
        this.setBindings(local,ENGINE_SCOPE);
        try {
            super.init();
        }
        catch (jbxml.Function.MethodNotFound exc){
            Throwable cause = exc.getCause();
            if (cause instanceof jela.JelaProgramException){

                jela.JelaProgramException compiler = (jela.JelaProgramException)cause;

                System.err.println(compiler.getSourceLineNumbered());

                throw exc;
            }
        }
    }
}
